var express = require('express');
const fs = require('fs');
var router = express.Router();
let cookie = require("cookie-parser");
var persons = fs.readFileSync("D:/Offcn/EP3/day10/xiaou/persons.json");
persons = JSON.parse(persons)
let svgCaptcha = require("svg-captcha");
let mysql = require("mysql");
let config = {
    host:"localhost",//数据库连接服务 
    port:3306,//数据库端口
    user:"root",//数据库用户名
    password:"root",//数据库连接密码
    database:"student",//选择你要使用的库房
}
let connection = mysql.createConnection(config);
connection.connect((err) => {
    if (err) {
        console.log("连接数据库失败")
    } else {
        console.log("数据库连接成功")
    }
})


router.use(cookie())

router.get("/svgcode", (req, res) => {
    let Captcha = svgCaptcha.create();
    // 使用cookie存储验证码的值
    res.cookie("code", Captcha.text);
    res.type("svg"); //使用svg格式生成图片
    res.send(Captcha.data); //将验证码发送给前端
})

router.get("/login", (req, res) => {
    //res.send("登录")
    res.render("pages/loginAndRegister/login.html")
})

router.post("/login", (req, res) => {
    let sql = `select * from member`; 
    connection.query(sql,(err,doc)=>{
        if (err) {
            console.log("查询失败")
        } else {
            if ((req.cookies.code).toUpperCase()==(req.body.code).toUpperCase()) {
                doc.find(v => v.username == req.body.username && v.password == req.body.password)?res.send("登录成功"):res.send("用户名密码错误")
            }else{
                res.send("验证码错误")
            } 
        }
    })
})


router.get("/reg", (req, res) => {
    //res.send("注册")
    res.render("pages/loginAndRegister/register.html")
})

router.post('/reg', (req, res) => {
    let sql = `select * from member`; 
    connection.query(sql,(err,doc)=>{
        if (err) {
            console.log("查询失败")
        } else {
            let flag = doc.find(val => val.username == req.body.username)
            if (flag) {
                res.send("用户名已经被占用")
            } else {
                res.send("注册成功")
                let{username,password}=req.body
                let sql = `insert into member (username,password) value ("${username}",${password})`
                connection.query(sql)
            }
        }

    })



})

module.exports = router;